import React, { useState, useEffect, useMemo, useRef } from "react";
import * as echarts from "echarts";
export default () => {
  const ref = useRef();
  const [chart, setChart] = useState(null);
  const [data, setData] = useState(null);
  const option = useMemo(() => {
    if (!data) return null;
    let op = {
      tooltip: {
        trigger: "item",
        // formatter:'人数占比:<br/>{b}: {d}%',
      },
      legend: {
        orient: "vertical",
        right: "15%",
        top: "center",
        // icon: "circle",
      },
      grid: {
        left: "0%",
        right: "10%",
        width: "100%",
        height: "100%",
      },
      series: [
        {
          name: "Access From",
          type: "pie",
          top: 0,
          bottom: 0,
          center: ["40%", "50%"],
          radius: ["40%", "70%"],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: "center",
            formatter: "人数占比\n{d}%",
          },
          emphasis: {
            label: {
              show: true,
              fontSize: "18",
              fontWeight: "bold",
            },
          },
          labelLine: {
            show: false,
          },
          data,
        },
      ],
    };
    return op;
  }, [data]);

  /*=======请求数据 =======*/
  const getData = () => {
    let lst = [{ name: "抖音" }, { name: "微信" }, { name: "微博" }, { name: "小红书" }];
    for (let i = 0; i < lst.length; i++) {
      lst[i].value = Math.round(Math.random() * 2000);
    }
    setData(lst);
  };

  /* ======== 定时改变data ======= */
  useEffect(() => {
    getData();
    let timer = setInterval(() => {
      getData();
    }, 3000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  /* ======== 生成图表实例 ======= */
  useEffect(() => {
    ref.current && setChart(echarts.init(ref.current));
  }, []);

  /* ======= 渲染图表 ====== */
  useEffect(() => {
    chart && option && chart.setOption(option);
  }, [chart, option]);

  return (
    <div style={{ width: "100%", height: "100%" }} ref={ref}></div>
  );
};
